package com.well.register.event;

import com.alibaba.fastjson.JSONObject;
import com.well.register.cluster.ClusterVote;
import com.well.register.data.ClusterDataCenter;
import com.well.register.data.DataCenter;
import com.well.rpc.model.ClusterServerModel;
import com.well.rpc.model.EnumServerStatus;
import com.well.rpc.model.EventType;
import com.well.rpc.model.TransData;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * 检测集群连接事件
 */
@Component
public class CheckClusterEvent implements AppEvent {
    Logger logger = LoggerFactory.getLogger(CheckClusterEvent.class);

    @Override
    public void doEvent(ChannelHandlerContext channelHandlerContext, TransData transData) {
        SocketAddress socketAddress = channelHandlerContext.channel().remoteAddress();
        ClusterServerModel serverModel = getServerModel(socketAddress, transData);
        // 注册集群信息

        ClusterDataCenter.setClusterServerModel(serverModel);
        registerSelf(serverModel);
        ClusterVote vote = new ClusterVote();
        vote.setPower();

        //集群选举
        logger.info("已连接集群：" + JSONObject.toJSONString(serverModel));
        logger.info("currentStatus :" + EnumServerStatus.enumServerStatus(ClusterDataCenter.getStatus()).name());
    }

    @Override
    public EventType eventType() {
        return EventType.CHECK_CLUSTER;
    }

    public ClusterServerModel getServerModel(SocketAddress socketAddress, TransData transData) {
        ClusterServerModel serverModel = JSONObject.parseObject(transData.getJsonData(), ClusterServerModel.class);

        InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
        String hostName = inetSocketAddress.getHostName();
        serverModel.setHost(hostName);
        return serverModel;
    }

    public void registerSelf(ClusterServerModel serverModel) {
        //将本节点也注册进去
        if (ClusterDataCenter.getIsRegisterSelf().get()) {
            return;
        }
        ClusterServerModel self = new ClusterServerModel();
        self.setHost(serverModel.getTargetHost());
        self.setIsUp(true);
        self.setAge(DataCenter.getStartTime());
        self.setPort(DataCenter.getPort());
        ClusterDataCenter.setClusterServerModel(self);
        ClusterDataCenter.getIsRegisterSelf().set(true);
    }
}
